
const pool = require('../index');
const YjxBaseModel = require('./YjxBaseModel');

class YjxActivityModel extends YjxBaseModel {

    constructor(obj) {
        super(obj);
    }

    // 取得表名
    getTableName(){
        return 'yjx_activity';
    };
    // 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
    getWhereConditionOfKeyEqual(){
        return 'act_id='+this.act_id;
    };


    /**
     * 获取单个活动的配置信息
     *
     * @author 王俊
     * @date 2018-06-08
     *
     * @param activityId 活动 id
     * @param callback  回调
     *          error: 查询失败
     *          data : yjx_activity + yjx_act_setting 行数据(部分字段重命名)
     */
    getSingleActivitySettingInfo (activityId, callback) {

        pool.getConnection(function(getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.getSingleActivitySettingInfo Err:'+getConErr);
                return callback(getConErr,null);
            }

            const sql =
                ' SELECT ya.act_id, ' +
                '        CASE ' +
                '            WHEN ya.state > 30 THEN ya.state ' +
                '            WHEN ya.start_time > SYSDATE() THEN 10 ' +
                '            WHEN ya.end_time <= SYSDATE() THEN 30 ' +
                '            ELSE 20 ' +
                '        END AS state, ' +
                '        ya.theme_img, ' +
                '        ya.url, ' +
                '        ya.title, ' +
                '        ya.desc, ' +
                '        DATE_FORMAT(ya.start_time, "%Y.%m.%d") AS startDate, ' +
                '        DATE_FORMAT(ya.end_time, "%Y.%m.%d") AS endDate, ' +
                '        UNIX_TIMESTAMP(ya.start_time) AS startTimestamp, ' +
                '        UNIX_TIMESTAMP(ya.end_time) AS endTimestamp, ' +
                '        ya.type, ' +
                '        ya.publish, ' +
                '        yas.platform_type, ' +
                '        ya.images, ' +
                '        yo.name AS org_name, ' +
                '        yas.as_id, ' +
                '        yas.reward_total, ' +
                '        yas.product_limit, ' +
                '        yas.field1, ' +
                '        yas.field2, ' +
                '        yas.field3, ' +
                '        yas.field4, ' +
                '        yas.field5, ' +
                '        yas.weight1, ' +
                '        yas.weight2, ' +
                '        yas.weight3, ' +
                '        yas.weight4, ' +
                '        yas.weight5, ' +
                '        yas.threshold1, ' +
                '        yas.threshold2, ' +
                '        yas.threshold3, ' +
                '        yas.threshold4, ' +
                '        yas.threshold5 ' +
                ' FROM yjx.yjx_activity ya, ' +
                '      yjx.yjx_act_setting yas, ' +
                '      yjx.yjx_org yo ' +
                ' WHERE ya.act_id = ' + activityId +
                '   AND yo.org_id = ya.org_id ' +
                '   AND yas.as_id = ya.as_id ' +
                '   AND ya.del_flg = 0 ' +
                // '   AND ya.publish = 1 ' + // 后台使用时, 活动可能取消发布
                '   AND yas.del_flg = 0 ';
            console.log(sql);
            connection.query(sql, function(queryErr, results) {
                // And done with the connection.
                connection.release();
                if(queryErr || !results || results.length <=0) {
                    console.log('YjxActivityModel.getSingleActivitySettingInfo error:'+queryErr);
                    return callback(queryErr||'该活动不存在');
                }
                return callback(queryErr, results[0]);
            });

        });
    };

    async getSingleActivitySettingInfoPromise (activityId) {

        const self = this;
        return new Promise((resolve, reject) => {
            self.getSingleActivitySettingInfo(activityId, (error, data) => {
                error ? reject(error) : resolve(data);
            });
        });
    };

    /**
     * 获取活动的统计信息
     *
     * @author 王俊
     * @date 2018-06-08
     *
     * @param {Object} option 请求参数
     * @param {Number} [option.activityId] 指定活动 id, 若传递此字段, 则只查询该活动
     * @param {Array} [option.activityIds] 指定活动 id 数组, 若传递此字段, 则可查询该组活动
     * @param {Function} callback 回调函数
     */
    getActivityStatisticsInfo (option, callback) {
        if(!option.activityId && (!option.activityIds || option.activityIds.length <= 0)) {
            return callback('参数错误', null);
        }
        pool.getConnection(function(getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.getActivityStatisticsInfo Err:'+err);
                return callback(getConErr,null);
            }

            let actCondition = '      AND yaup.act_id = ' + option.activityId;
            if(option.activityIds && option.activityIds.length > 0) {
                actCondition = '      AND yaup.act_id in ( ' + option.activityIds.join(',') + ') ';
            }
            const sql =
                ' SELECT count(yaup.aup_id) AS totalProducts, ' +
                '        sum(yaup.data1) AS totalData1, ' +
                '        sum(yaup.data2) AS totalData2, ' +
                '   (SELECT count(DISTINCT (yaup.user_id)) ' +
                '    FROM yjx.yjx_act_user_product yaup ' +
                '    WHERE yaup.del_flg = 0 ' +
                actCondition +
                '      AND yaup.state = 30) AS totalUsers ' +
                ' FROM yjx.yjx_act_user_product yaup ' +
                ' WHERE yaup.del_flg = 0 ' +
                actCondition +
                '   AND yaup.state = 30 ';
            console.log(sql);
            connection.query(sql, function(queryErr, results) {
                // And done with the connection.
                connection.release();
                if(queryErr || !results || results.length <=0) {
                    console.log('YjxActivityModel.getActivityStatisticsInfo error:'+queryErr);
                    callback(queryErr||'暂无统计信息');
                }
                return callback(queryErr, results[0]);
            });

        });
    };


    /**
     * 获取活动列表sql
     *
     * @param bForCnt  标记是否需要分页
     * @param {Object}  param 筛选活动的参数列表
     * @param {Array}  param.states    活动状态数组10未开场、20已开场、30活动截止、40活动关闭、50活动取消 数组的json字符串
     * @param {Number} param.pageNum   页码
     * @param {Number} param.pageSize  页容量
     * @param {Number} [param.userId]  用户id
     * @param {Number} [param.filterUser] 是否根据用户过滤活动列表, 0 不过滤, 1 过滤, 如使用该字段必须传递 userId
     * @param {Number} [param.checkReward] 是否检测用户在活动中的获奖状况,0 不过滤, 1 过滤,  如使用该字段必须传递 userId
     * @param {Number} param.withTotalPage 是否需要返回总页数  0不需要  1需要
     * @param {Number} param.orgId 组织id该接口不适用该参数
     * @param {Number} param.flag 用来标记当前接口需要使用publish字段
     * @returns {string}
     */
    sql_getActivityList(bForCnt,param) {

        let sql = '';
        if(bForCnt) {
            sql += " SELECT " +
                "   COUNT(DISTINCT res.id) AS `count` ";
        } else  {
            sql += "SELECT DISTINCT *  " ;
        }
        sql +=  " FROM " +
            "	( SELECT	" +
            "	  act.act_id AS id,	" +
            "	  act.act_no AS actNo,	" +
            "	  act.title,	" +
            "	  act.theme_img AS thumb,	" +
            "	  act.url,	" +
            "	  yo.name AS orgName,	" +
            "	  DATE_FORMAT(act.start_time, '%Y.%c.%d') AS startDate,	" +
            "	  DATE_FORMAT(act.end_time, '%Y.%c.%d') AS endDate,	" +
            "	  UNIX_TIMESTAMP(act.start_time) AS startTimestamp,	" +
            "	  UNIX_TIMESTAMP(act.end_time) AS endTimestamp,	" +
            "	  CASE	" +
            "	    WHEN act.state > 30	" +
            "	    THEN act.state	" +
            "	    WHEN act.start_time > SYSDATE()	" +
            "	    THEN 10	" +
            "	    WHEN act.end_time <= SYSDATE()	" +
            "	    THEN 30	" +
            "	    ELSE 20	" +
            "	  END AS state,	" +
            "     IFNULL(yas.reward_total,0) AS rewardTotal, " +
            "     IFNULL(yast.show_view_cnt,0) AS viewCnt, " +
            "     act.order,  "+
            "     act.create_time  "+
            "	FROM	" ;
        if (param.userId && param.filterUser && param.userId>0){
            sql += " yjx.yjx_act_user_product yaup,";
        }
        sql +=   "	  yjx.yjx_org yo,	" +
            " yjx.yjx_activity act	" +
            "   LEFT JOIN yjx.yjx_act_setting yas ON yas.as_id = act.as_id  AND yas.del_flg = 0   " +
            "   LEFT JOIN yjx.yjx_act_stats yast ON act.act_id = yast.act_id  AND yast.del_flg = 0   " +
            "	WHERE  act.del_flg = 0	" ;
        if (param.userId && param.filterUser && param.userId>0){
            sql += " AND yaup.act_id = act.act_id" +
                "    AND yaup.del_flg = 0" +
                "    AND yaup.user_id = "+param.userId+" ";
        }
        if (param.flag){
            sql+=" AND act.publish = 1 "
        }
        sql += "	  AND yo.del_flg = 0	" +
            "	  AND act.org_id = yo.org_id	" ;
        if (param.orgId && param.orgId>0){
            sql += "  AND  yo.org_id = "+param.orgId+" ";
        }
        if(param.states && param.states.length > 0) {
            let  term = " AND (";
            for (let i = 0; i < param.states.length; i++) {
                const state = param.states[i];
                if (state == 10) {
                    term += "   ( now() < act.start_time AND act.state < 40 ) or ";
                }
                if (state == 20) {
                    term += "  ( (now() > act.start_time and now() < act.end_time ) AND act.state < 40 ) or ";
                }
                if (state == 30) {
                    term += "  (now() > act.end_time AND act.state < 40 ) or ";
                }
                if (state == 40) {
                    term += "  act.state = 40 or ";
                }
                if (state == 50) {
                    term += "  act.state = 50  or ";
                }
                if (state == 60) {
                    term += "  act.state = 60  or ";
                }
            }
            term = term.substring(0, term.lastIndexOf('or '));
            term += " )";
            sql += term;
        }
        sql += " ) res " ;
        sql +="  ORDER BY res.order ASC,res.create_time DESC " ;
        if (!bForCnt) {
            if (typeof param.pageNum !== 'undefined' && param.pageNum !== null &&
                typeof param.pageSize !== 'undefined' && param.pageSize !== null)
            {
                const skipCnt = Number(param.pageNum||'0') * Number(param.pageSize||'0');
                sql += " LIMIT " + skipCnt + "," + Number(param.pageSize||'0');
            }
        }
        return sql;
    }


    /**
     * 获取活动列表
     *
     * @author 毛凯
     * @date 2018-6-11
     *
     * @param {Object}  param 筛选活动的参数列表
     * @param {Array}  param.states    活动状态数组10未开场、20已开场、30活动截止、40活动关闭、50活动取消 数组的json字符串
     * @param {Number} param.pageNum   页码
     * @param {Number} param.pageSize  页容量
     * @param {Number} [param.userId]  用户id
     * @param {Number} [param.filterUser] 是否根据用户过滤活动列表, 0 不过滤, 1 过滤, 如使用该字段必须传递 userId
     * @param {Number} [param.checkReward] 是否检测用户在活动中的获奖状况,0 不过滤, 1 过滤,  如使用该字段必须传递 userId
     * @param {Number} param.withTotalPage 是否需要返回总页数  0不需要  1需要
     * @param {Number} param.orgId 组织id该接口不适用该参数
     * @param {Number} param.flag 用来标记当前接口需要使用publish字段
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getActivityList(param,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getActivityList] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = sql_getActivityList(false,param);
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityList] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };
    /**
     * 获取活动数量
     *
     * @author 毛凯
     * @date 2018-6-11
     *
     * @param {Object}  param 筛选活动的参数列表
     * @param {Array}  param.states    活动状态数组10未开场、20已开场、30活动截止、40活动关闭、50活动取消 数组的json字符串
     * @param {Number} param.pageNum   页码
     * @param {Number} param.pageSize  页容量
     * @param {Number} [param.userId]  用户id
     * @param {Number} [param.filterUser] 是否根据用户过滤活动列表, 0 不过滤, 1 过滤, 如使用该字段必须传递 userId
     * @param {Number} [param.checkReward] 是否检测用户在活动中的获奖状况,0 不过滤, 1 过滤,  如使用该字段必须传递 userId
     * @param {Number} param.withTotalPage 是否需要返回总页数  0不需要  1需要
     * @param {Number} param.orgId 组织id该接口不适用该参数
     * @param {Number} param.flag 用来标记当前接口需要使用publish字段
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getActivityListCnt(param,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getActivityListCnt] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = sql_getActivityList(true,param);
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results[0].count);
            });
        })
    };


//***************************************************************************************************************
    /**
     * 获取活动列表sql
     *
     * @param bForCnt  标记是否需要分页
     * @param {Object} param 筛选活动的参数列表
     * @param {Number} param.pageNum   页码
     * @param {Number} param.pageSize  页容量
     * @param {Array}  param.findStates 活动状态数组[10未开场、20已开场、30活动截止、40活动关闭、50活动取消、60活动筹备中]
     * @param {Number} [param.withRewardInfo] 是否返回活动奖励信息
     * @param {Number} param.coopOrgId 合作组织id(如网红公司)
     * @returns {string}
     */
    sql_getActList_2(bForCnt,param) {

        let sql = '';
        if(bForCnt) {
            sql += " SELECT COUNT(xx.act_id) AS `count` ";
        } else  {
            sql += " SELECT xx.* " ;
        }
        sql +=  " FROM " +
            " ( SELECT " +
            "	act.act_id,act.act_no,act.type,act.org_id,r.`name`,act.as_id,act.state,act.title, " +
            "	DATE_FORMAT(act.start_time, '%Y-%m-%d %H:%i:%s') AS start_time, " +
            "	DATE_FORMAT(act.end_time, '%Y-%m-%d %H:%i:%s') AS end_time, " +
            " 	case when act.state>30 then act.state " +
            " 		 when act.start_time>sysdate() then 10 " +
            " 	     when act.end_time<=sysdate() then 30 " +
            " 	     else 20 " +
            " 	end AS valid_state, " +
            " 	act.desc,act.theme_img,act.images,act.url,act.`order`,act.publish, " +
            " 	DATE_FORMAT(act.create_time,'%y/%m/%d %H:%i:%s') AS create_time, " +
            " 	DATE_FORMAT(act.update_time,'%y/%m/%d %H:%i:%s') AS update_time ";

        // 奖励信息
        if(param.withRewardInfo) {
            // reward1: 已发放的奖励
            sql += " ,IFNULL( " +
                " 	(SELECT SUM(IFNULL(aur.`bal_reward`,0)) " +
                " 	FROM yjx.yjx_act_user_reward aur  " +
                " 	WHERE aur.act_id = act.act_id ";
            if(param.coopOrgId && param.coopOrgId>0) {
                sql += " AND aur.org_id= "+param.coopOrgId;
            }
            sql += " 	AND aur.bal_flg=1 " +
                " 	AND aur.del_flg=0) " +
                " 	, 0) AS reward1 ";
            // reward2: 已提现的奖励
            sql += " ,IFNULL( " +
                " 	(SELECT SUM(IFNULL(afh.`cash_amt`,0)) " +
                " 	FROM yjx.yjx_act_user_reward aur " +
                " 	INNER JOIN yjx.yjx_act_finance_his afh " +
                " 		ON afh.aur_id=aur.aur_id " +
                " 		AND afh.state=10  " +
                " 		AND afh.cash_state=20  " +
                " 		AND afh.del_flg=0 " +
                " 	WHERE aur.act_id = act.act_id ";
            if(param.coopOrgId && param.coopOrgId>0) {
                sql += " AND aur.org_id= "+param.coopOrgId;
            }
            sql += " 	AND aur.bal_flg=2 " +
                " 	AND aur.del_flg=0) " +
                " 	, 0) AS reward2 ";
        }

        sql += " FROM " +
            " 	yjx.yjx_activity act " +
            " 	LEFT JOIN yjx.yjx_org r " +
            " 	    ON r.org_id = act.org_id and r.del_flg=0 " +
            " WHERE " +
            " 	act.del_flg = 0 ";
        if(param.actId && param.actId>0) {
            sql += " 	and act.act_id= "+param.actId;
        }
        if(param.type && param.type>0) {
            sql += " 	and act.type= "+param.type;
        }
        if(param.state && param.state>0) {
            sql += " 	and act.state= "+param.state;
        }
        if(param.title && (param.title||'').length>0) {
            sql += " 	and act.title like CONCAT('%','" +param.title+ "','%') ";
        }
        if(param.hasOwnProperty('publish')) {
            sql += "	and act.publish= "+param.publish;
        }
        if(param.coopOrgId && param.coopOrgId>0) {
            sql += " AND act.`act_id` IN (" +
                " 	SELECT DISTINCT p.act_id " +
                " 	FROM yjx.yjx_act_user_product p " +
                " 	WHERE p.del_flg=0 " +
                " 	AND p.state=30 " +
                " 	AND p.org_id= "+param.coopOrgId +") ";
        }
        sql += " ) xx ";

        // 准确活动状态不直接用"state"字段判断, 用sql中的"valid_state"判断
        if(param.findStates && param.findStates.length>0) {
            sql += " WHERE xx.valid_state IN ("+(param.findStates.join(','))+") ";
        }

        sql += " ORDER BY xx.order, xx.act_id DESC " ;
        if (!bForCnt) {
            if (typeof param.pageNum !== 'undefined' && param.pageNum !== null &&
                typeof param.pageSize !== 'undefined' && param.pageSize !== null)
            {
                const skipCnt = Number(param.pageNum||'0') * Number(param.pageSize||'0');
                sql += " LIMIT " + skipCnt + "," + Number(param.pageSize||'0');
            }
        }
        return sql;
    }
// 获取活动列表Cnt
    getActListCnt_2(param,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getActListCnt_2] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = sql_getActList_2(true,param);
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActListCnt_2] queryErr' + queryErr)
                }
                return callback(queryErr, results[0].count);
            });
        })
    };
// 获取活动列表信息
    getActList_2(param,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getActList_2] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = sql_getActList_2(false,param);
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActList_2] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };
//***************************************************************************************************************


    /**
     * 统计用户获奖作品的个数与获奖的总奖金
     *
     * @author 毛凯
     * @date 2018-6-11
     *
     * @param activityId 活动id
     * @param userId  用户id
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getUserRewardCntAndUserDoc(activityId,userId,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getActivityListCnt] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = "	select	" +
                "	  a.rewardProductCnt,	" +
                "	  b.totalRewardAmount	" +
                "	from	" +
                "	  (select	" +
                "	    count(user_id) as rewardProductCnt	" +
                "	  from	" +
                "	    yjx.yjx_act_user_product yaup	" +
                "	  where yaup.user_id = "+userId+"	" +
                "	    and act_id = "+activityId+"	" +
                "	    and yaup.del_flg = 0	" +
                "       AND yaup.state  = 30 " +
                "	    and yaup.reward_amt > 0) a,	" +
                "	  (SELECT	" +
                "	    SUM(yaup.reward_amt) AS totalRewardAmount	" +
                "	  FROM	" +
                "	    yjx.yjx_act_user_product yaup	" +
                "	  WHERE yaup.del_flg = 0	" +
                "	    AND yaup.act_id = "+activityId+"	" +
                "	    AND yaup.user_id = "+userId+" ) b	" ;
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };

    /**
     * 统计组织下所有发布活动以及参加所有作品
     *
     * @author 毛凯
     * @date 2018-6-11
     *
     * @param orgId 组织id
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getOrgActivityCntAndProductCnt(orgId,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getActivityListCnt] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = "	SELECT 	" +
                "	 a.*,	" +
                "	 b.*	" +
                "	 FROM	" +
                "	(SELECT	" +
                "	  COUNT(ya.act_id) AS totalActivity	" +
                "	FROM	" +
                "	  yjx.yjx_activity ya	" +
                "	WHERE ya.org_id = "+orgId+"	" +
                "	AND ya.del_flg = 0) a,	" +
                "	(SELECT	" +
                "	  COUNT(yaup.aup_id) AS totalProducts	" +
                "	FROM	" +
                "	  yjx.yjx_activity ya,	" +
                "	  yjx.yjx_act_user_product yaup	" +
                "	WHERE ya.org_id = "+orgId+"	" +
                "	  AND ya.act_id = yaup.act_id	" +
                "	  AND ya.del_flg = 0	" +
                "	  AND yaup.state = 30	" +
                "	  AND yaup.del_flg = 0) b	" ;
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };

    /**
     * 获取组织下所有活动id
     *
     * @author 毛凯
     * @date 2018-6-11
     *
     * @param orgId  组织id
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getOrgActivityAllId(orgId,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getActivityListCnt] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            let sql = "	SELECT	" +
                "	  ya.act_id	" +
                "	FROM	" +
                "	  yjx.yjx_activity ya	" +
                "	WHERE  ya.del_flg = 0	" ;
            if(orgId && orgId > 0){
                sql +=  "   AND ya.org_id = "+orgId+" ";
            }
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };

    /**
     * 统计每个活动中参与的总人数
     *
     * @author 毛凯
     * @date 2018-6-11
     *
     * @param orgId  组织id
     * @param actId  活动id
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getOrgActivityAllUser(orgId,actId,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getOrgActivityAllUser] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = "	SELECT	" +
                "	  COUNT(DISTINCT yaup.user_id) as `count`	" +
                "	FROM	" +
                "	  yjx.yjx_activity ya,	" +
                "	  yjx.yjx_act_user_product yaup	" +
                "	WHERE ya.org_id = "+orgId+"	" +
                "	AND ya.act_id  = "+actId+"	" +
                "	AND yaup.state  = 30	" +
                "	AND ya.act_id = yaup.act_id 	" ;
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results[0].count);
            });
        })
    };

    /**
     * 统计每个活动中参与的总人数
     *
     * @author 毛凯
     * @date 2018-6-11
     *
     * @param actId  活动id
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getOrgActivityCntInfo(actId,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getOrgActivityCntInfo] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = "	SELECT	" +
                "	  a.totalUser,	" +
                "	  b.totalProducts	" +
                "	FROM	" +
                "	  (SELECT	" +
                "	    COUNT(DISTINCT yaup.user_id) AS totalUser	" +
                "	  FROM	" +
                "	    yjx.yjx_act_user_product yaup	" +
                "	  WHERE yaup.act_id = "+actId+"	" +
                "	    AND yaup.state = 30	" +
                "	    AND yaup.del_flg = 0) a,	" +
                "	  (SELECT	" +
                "	    COUNT(yaup.aup_id) AS totalProducts	" +
                "	  FROM	" +
                "	    yjx.yjx_act_user_product yaup	" +
                "	  WHERE yaup.del_flg = 0	" +
                "	    AND yaup.state = 30	" +
                "	    AND yaup.act_id = "+actId+") b	" ;
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };


    /**
     * 关闭活动
     *
     * @author 毛凯
     * @date 2018-6-14
     *
     * @param actId  活动id
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    updActivityState(actId,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getOrgActivityAllUser] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            const sql = " UPDATE " +
                "  yjx.yjx_activity ya " +
                " SET "+
                "    ya.state = 40 " +
                " WHERE act_id = "+actId+" " +
                "  AND ya.del_flg = 0 ";
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };

    /**
     * 获取活动的推广码配置信息
     *
     * @author 毛凯
     * @date 2018-7-4
     *
     * @param actId  活动id
     * @param callback 回调
     *           err: 查询失败
     *           results: 活动列表
     *
     * */
    getActivityCouponInfo(actId,callback){
        pool.getConnection(function (getConErr, connection) {
            if (getConErr) {
                console.log('YjxActivityModel.js [getOrgActivityAllUser] getConErr' + getConErr);
                return callback(getConErr, null);
            }
            let sql = "	SELECT	" +
                "	  ya.act_id,	" +
                "	  ya.title,	" +
                "	  yarf.max,	" +
                "	  yarf.reward_amt	" +
                "	FROM	" +
                "	  yjx.yjx_activity ya,	" +
                "	  yjx.yjx_act_setting yas,	" +
                "	  yjx.yjx_act_reward_rule yarf	" +
                "	WHERE ya.as_id = yas.as_id	" +
                "	AND yas.as_id = yarf.as_id	" +
                "	AND yarf.type = 20	" +
                "	AND ya.del_flg = 0 	" +
                "	AND yas.del_flg = 0	" +
                "	AND yarf.del_flg = 0	" ;
            if (actId && actId>0){
                sql+= "	AND ya.act_id = "+actId+"	" ;
            }
            console.log(sql);
            connection.query(sql, function (queryErr, results) {
                connection.release();
                if (queryErr) {
                    console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
                }
                return callback(queryErr, results);
            });
        })
    };
}







module.exports = YjxActivityModel;

